package com.bw.http

import android.os.Environment
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.base.constants.ApiConst
import com.bw.base.constants.HttpConst
import com.bw.base.constants.RoutePath
import com.google.gson.Gson
import com.tencent.mmkv.MMKV
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

object RetrofitUtils {

    private val httpClientInstance: OkHttpClient by lazy {
        val builder = OkHttpClient.Builder().apply {
            connectTimeout(HttpConst.CONNECT_TIME_OUT, TimeUnit.SECONDS)
            readTimeout(HttpConst.READ_TIME_OUT, TimeUnit.SECONDS)
            writeTimeout(HttpConst.WRITE_TIME_OUT, TimeUnit.SECONDS)


            addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))


            //Header参数拦截器
            addInterceptor(getHeaderInterceptor())

            //服务器异常拦截器
            addInterceptor(getServiceExceptionInterceptor())


            val storeFile = getExternalStoreFile()
            if (storeFile != null) {
                //10m缓存
                cache(Cache(storeFile, 10 * 1024 * 1024))
            }


        }
        builder.build()
    }

    /**
     * Retrofit实例
     */
    private val retrofitInstance: Retrofit by lazy {
        Retrofit.Builder().apply {
            baseUrl(ApiConst.BASE_URL)
            client(httpClientInstance)
            addConverterFactory(GsonConverterFactory.create())

        }.build()
    }

    // 通过泛型动态创建 ApiService 实例
    fun <T> createService(serviceClass: Class<T>): T {
        return retrofitInstance.create(serviceClass)
    }



    private fun getExternalStoreFile(): File? {
        val externalStorageFile = Environment.getExternalStorageDirectory()
        if (externalStorageFile.exists()) return File(externalStorageFile, "park_network_cache")
        return null

    }


    /**
     * 请求头拦截器
     */
    private fun getHeaderInterceptor(): Interceptor {
        return object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {

                val builder = chain.request().newBuilder()


                val token = MMKV.defaultMMKV().decodeString(ApiConst.PARAM_TOKEN, "")
                if (token != null) {
                    builder.header(ApiConst.PARAM_TOKEN, token)
                }

                val request = builder.build()
                val response = chain.proceed(request)

                //验证token是否过期
                if (response.code == 403 || response.code == 401) {
                    ARouter.getInstance().build(RoutePath.PATH_LOGIN).navigation()
                }

                return response
            }
        }
    }


    /**
     * 服务器异常拦截器
     */
    private fun getServiceExceptionInterceptor(): Interceptor {
        return object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {


                val errorResponse = chain.proceed(chain.request())
                val builder = errorResponse.newBuilder()

                if (errorResponse.code == 500) {
                    val res = Res(500, "服务器异常", "请联系客服")

                    builder.body(
                        Gson().toJson(res)
                            .toResponseBody("application/json;charset=UTF-8".toMediaTypeOrNull())
                    )
                }

                return errorResponse
            }
        }
    }

}